<?php
/**
 * File description.
 * 
 * @filesource
 * @author Michael N <webjestic@gmail.comt>
 * @link http://webjestic.net webJestic
 * @license http://www.opensource.org/licenses/bsd-license.php BSD
 * @copyright Copyright (c) 2009 - webJestic.NET.  All Rights Reserved.
 * 
 * 
 * @category   Engine
 * @package    Resources
 * @subpackage Session 
 */


class Engine_Resource_Session extends Zend_Application_Resource_ResourceAbstract {
	
	protected $_session;
	
	public function init() {
		return $this->getSession();		
	}
	
	
	public function getSession() {
		// Prepare session config to work with the database
		$config = array(
		    'name'           => CORE_SESSIONS,
		    'primary'        => 'session_id',
		    'modifiedColumn' => 'session_modified',
		    'lifetimeColumn' => 'session_lifetime',
		    'dataColumn'     => 'session_data'
		);
 
		// Initialize the session adapter 
		Zend_Db_Table_Abstract::setDefaultAdapter(Zend_Registry::get('Zend_Db'));
		Zend_Session::setSaveHandler(new Zend_Session_SaveHandler_DbTable($config));
		
		// Load and configure the Session
		$this->setSessionConfig();
		
		// Delete expired sessions
		$this->deleteExpired();
		
		// Create session
		return $this->createSession();
	}
	
	
	public function createSession() {
		// Start the session and generate new ID
		Zend_Session::start();
		Zend_Session::regenerateId();
		
		// Create a default sesson namespace
		$this->_session = new Zend_Session_Namespace();	
		return $this->_session;
	}
	
	public function restartSession() {
		
	}
	
	
	protected function setSessionConfig() {
		// Load the config options from the application.ini
		$config = $this->getOptions();
		$config['name'] = md5($config['name'] . SITE_SALT);
		Zend_Session::setOptions($config);
	}
	
	
	protected function deleteExpired() {
		$core_sessions = new Engine_Db_Table_CoreSessions();
		$i = $core_sessions->delete("session_timestamp < DATE_SUB(CURDATE(), INTERVAL 2 DAY)");
	}
}

?>